package device

import (
	"encoding/json"
	"errors"
	"reflect"
	"time"
)

// 定时 {"time":1543370493,"start":"11:00","end":"12:00","wkocc":"1111100","state":1,"loop":"n","tasknoc":"5bfdf6fdc175f423ef3acc84"}
type Timing struct {
	Command
	Start string `json:"start"`
	End   string `json:"end"`
	Wkocc string `json:"wkocc"`
	State int64  `json:"state"`
	Loop  int64  `json:"loop"`
}

func (d *Timing) Parser(m interface{}, action int) error {
	if reflect.ValueOf(m).Type().String() != "*models.Timing" {
		return errors.New("m Must be *models.Timing struct.")
	}

	d.Type = TYPE_TIMING
	d.Time = time.Now().Unix()

	d.Wkocc = reflect.ValueOf(m).Elem().FieldByName("Wkocc").String()
	d.Start = reflect.ValueOf(m).Elem().FieldByName("Start").String()
	d.End = reflect.ValueOf(m).Elem().FieldByName("End").String()
	d.Tasknoc = reflect.ValueOf(m).Elem().FieldByName("Id").String()
	d.Done = CreateSign()
	d.State = reflect.ValueOf(m).Elem().FieldByName("State").Int()
	d.Loop = reflect.ValueOf(m).Elem().FieldByName("State").Int()
	d.Action = int64(action)

	return nil
}

func AddTiming(m interface{}) error {
	return sendTiming(INSERT, m)
}

func UpdateTiming(m interface{}) error {
	return sendTiming(UPDATE, m)
}

func DelTiming(m interface{}) error {
	return sendTiming(DELETE, m)
}

func sendTiming(action int, m interface{}) error {
	dl := Timing{}
	err := dl.Parser(m, action)
	if err != nil {
		return err
	}

	payload, err := json.Marshal(dl)
	if err != nil {
		DelSign(dl.Done)
		return err
	}

	return dl.SendCommand(reflect.ValueOf(m).Elem().FieldByName("Sta").String(), string(payload), 1, false)
}
